package net.NingXiaRuiTai.ShortChain.server.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.NingXiaRuiTai.ShortChain.controller.request.AccountRegisterRequest;
import net.NingXiaRuiTai.ShortChain.controller.request.LoginRequest;
import net.NingXiaRuiTai.ShortChain.enums.AuthTypeEnum;
import net.NingXiaRuiTai.ShortChain.enums.BizCodeEnum;
import net.NingXiaRuiTai.ShortChain.enums.SendCodeEnum;
import net.NingXiaRuiTai.ShortChain.manager.AccountManager;
import net.NingXiaRuiTai.ShortChain.model.AccountDO;
import net.NingXiaRuiTai.ShortChain.model.LoginUser;
import net.NingXiaRuiTai.ShortChain.server.AccountService;
import net.NingXiaRuiTai.ShortChain.server.NotifyServer;
import net.NingXiaRuiTai.ShortChain.utils.CommonUtil;
import net.NingXiaRuiTai.ShortChain.utils.IdUtil;
import net.NingXiaRuiTai.ShortChain.utils.JsonData;
import net.NingXiaRuiTai.ShortChain.utils.JwtUtil;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yuan
 * @since 2025-01-13
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {
    @Autowired
    private NotifyServer notifyServer;
    @Autowired
    private AccountManager accountManager;

    /**
     * 处理用户注册请求
     *
     * @param registerRequest 包含用户注册信息的请求对象
     * @return 表示注册操作结果的JsonData对象
     */
    @Override
    public JsonData register(AccountRegisterRequest registerRequest) {
    /*
    * ⼿机验证码验证
    * 密码加密（TODO）
    * 账号唯⼀性检查(TODO)
    * 插⼊数据库
    * 新注册⽤户福利发放(TODO)
    *
    * */
        boolean checkCode = false;
        //判断验证码
        if (StringUtils.isNotBlank(registerRequest.getPhone())){
            checkCode = notifyServer.checkCode(SendCodeEnum.USER_REGISTER, registerRequest.getPhone(), registerRequest.getCode());

        }
        //验证码错误
        if (!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        //
        AccountDO accountDO = new AccountDO();
        //将请求对象中的属性复制到accountDO对象中
        BeanUtils.copyProperties(registerRequest,accountDO);
        //认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());
        //设置账号 账号是唯一的，所以要进行唯一性检查 TODO 简单处理，之后重新设计
        accountDO.setAccountNo(Long.valueOf(IdUtil.generateId().toString()));
        //设置密码 盐
        accountDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));
        //设置密码 加密
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(),accountDO.getSecret());
        accountDO.setPwd(cryptPwd);
        //插入到数据库中
        int rows = accountManager.insertAccount(accountDO);
        log.info("rows:{},新⽤户注册:【{}】",rows,accountDO);
        //用户注册成功，发放福利
        userRegisterWelfare(accountDO);
        
        
        return JsonData.buildSuccess();
    }
    /*
    * 根据手机号去找
    *
    * */
    @Override
    public JsonData login(LoginRequest loginRequest) {
        List<AccountDO> accountDOList = accountManager.findByPhone(loginRequest.getPhone());
        if (accountDOList!=null&&accountDOList.size()==1){
            //获取到账号信息
            AccountDO accountDO = accountDOList.get(0);
            //密码加密
            String cryptPwd = Md5Crypt.md5Crypt(loginRequest.getPwd().getBytes(),accountDO.getSecret());
            if (cryptPwd.equals(accountDO.getPwd())){
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO,loginUser);

                //生成Token
                String token = JwtUtil.genJsonWebToken(loginUser);

                //token令牌返回给前端
                return JsonData.buildSuccess(token);
            }
        }else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
        return null;
    }

    /*
    * 用户初始化，发放福利：流量包 TODO
    *@param accountDO 新注册用户的账户信息
    * */
    private void userRegisterWelfare(AccountDO accountDO) {
    }
}
